package org.gwc.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 拦截器
 * 1、先实现拦截器接口HandlerInterceptor，按需实现preHandle、postHandle、afterCompletion
 * 2、在WebMvcConfigurer接口实现类中，注册拦截器addInterceptors
 * 3、handler发生异常时，不走postHandle
 */
public class MyInterceptor implements HandlerInterceptor {

    /**
     * 执行handler之前，调用的拦截方法
     *
     * 用途：编码格式设置、登录保护、权限处理
     *
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 我们要调用的方法对象
     * @return true 放行 false 拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;
    }

    /**
     * handler执行完毕之后，调用的方法 只能处理数据，不能阻碍过程进行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView 返回的视图和共享预数据对象
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    /**
     * 整体处理完毕
     * @param request
     * @param response
     * @param handler
     * @param ex handler报错了，异常对象
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
